from django.http import QueryDict
from django.shortcuts import redirect
from rest_framework import status, viewsets
from rest_framework.decorators import api_view 
from rest_framework.response import Response
from rest_framework.request import Request
from full_url.grabber import RequestGrabber
from .common import MiddlewareAPI
from .serializers import HomeCarouselSerializer, PrimaryClassificationSerializer, SecondaryClassificationSerializer, HotSearchKeywordSerializer
from .models import HomeCarousel, PrimaryClassification, SecondaryClassification, HotSearchKeyword

middleWareAPI = MiddlewareAPI()

#重定向 路由
def redirect_url(request):
  return redirect('/cuppon_api/api/')

# 商品列表
@api_view(['POST',])
def showGoodsList(request):
  params = get_parameter_dic(request)
  if ('page' in params.keys()) and ('page_size' in params.keys()):
    keyword_of_params = ''
    if 'keywords' in params.keys():
      keyword_of_params = params['keywords']
    result = get_goods_lists(keyword_of_params, params['page'], params['page_size'])
    return Response(result)
  return Response('bad request', status=status.HTTP_400_BAD_REQUEST)

# 商品优惠劵的详情
@api_view(['POST',])
def showCouponDetail(request):
  params = get_parameter_dic(request)
  if 'ulandUrl' in params:
    result = middleWareAPI.get_cunpon_details(params['ulandUrl'])
    return Response(result)
  return Response('bad request', status=status.HTTP_400_BAD_REQUEST)

# 商品详情
@api_view(['POST',])
def showGoodsDetail(request):
  # params = get_parameter_dic(request)
  # if 'goods_id' in params and 'ulandUrl' in params:
  #   result = middleWareAPI.get_goods_detail(params['goods_id'])
  #   result2 = middleWareAPI.get_cunpon_details(params['ulandUrl'])
  #   if result and result2['success']:
  #     result2['data']['images'] = result['data']['item']['images']
  #     if 'rate' in result['data'] and 'keywords' in result['data']['rate']:
  #       result2['data']['rate_keywords'] = result['data']['rate']['keywords']
  #     else:
  #       result2['data']['rate_keywords'] = []
  #     result2['data']['evaluates'] = result['data']['seller']['evaluates']
  #   return Response(result2)
  # return Response('bad request', status=status.HTTP_400_BAD_REQUEST)
  params = get_parameter_dic(request)
  if 'goods_id' in params:
    result = middleWareAPI.get_goods_detail(params['goods_id'])
    details_result = {}
    if 'rate' in result['data'] and 'keywords' in result['data']['rate']:
      details_result['rate_keywords'] = result['data']['rate']['keywords']
    else:
      details_result['rate_keywords'] = []
    details_result['evaluates'] = result['data']['seller']['evaluates']
    details_result['images'] = result['data']['item']['images']
    return Response({'data': details_result, 'message': None, 'success': True})
  return Response({'data': [], 'message': 'bad request', 'success': False})


# 生成淘口令
@api_view(['POST',])
def get_tao_pwd(request):
  params = get_parameter_dic(request)
  if 'uland' in params:
    result = middleWareAPI.get_tao_password(params['uland'])
    return Response(result)
  return Response('bad request', status=status.HTTP_400_BAD_REQUEST)

# 首页轮播图接口
@api_view(['GET',])
def get_home_carousel(request):
  home_carousel = HomeCarousel.objects.filter(is_show=True)
  serializer = HomeCarouselSerializer(home_carousel, many=True)
  url_parts = RequestGrabber(request)
  for item in serializer.data:
    item['car_img'] = url_parts.protocol() + url_parts.domain() + item['car_img']
  return Response(serializer.data)

# 获取一级分类
@api_view(['GET',])
def get_primary_classify(request):
  classify = PrimaryClassification.objects.filter(is_show=True)
  serializer = PrimaryClassificationSerializer(classify, many=True)
  url_parts = RequestGrabber(request)
  for item in serializer.data:
    item['category_ico'] = url_parts.protocol() + url_parts.domain() + item['category_ico']
  return Response(serializer.data)

#获取二级分类
@api_view(['POST',])
def get_second_classify(request):
  upper = get_parameter_dic(request)
  if 'upper_level_id' in upper:
    classifys = SecondaryClassification.objects.filter(upper_level_id=upper['upper_level_id'])
    serializer = SecondaryClassificationSerializer(classifys, many=True)
    return Response(serializer.data)
  return Response('bad request', status=status.HTTP_400_BAD_REQUEST)


# 获取搜索结果
@api_view(['GET',])
def get_search_auto_result(request):
  params = get_parameter_dic(request)
  result = middleWareAPI.get_search_auto_result(params['search_query'])
  if 'result' in result:
    return Response({'success': True,'data': result, 'message': None})
  return Response('bad request', status=status.HTTP_400_BAD_REQUEST)

# 热门搜索
@api_view(['POST',])
def hot_search_keyword(request):
  hot_keyword = HotSearchKeyword.objects.filter(is_show=True)
  serializer = HotSearchKeywordSerializer(hot_keyword, many=True)
  if serializer.data:
    return Response({'success': True, 'data': serializer.data, 'message': None})
  return Response('bad request', status=status.HTTP_400_BAD_REQUEST)


# 获取商品列表公共方法
def get_goods_lists(keyword, page, size):
  return middleWareAPI.get_index_goods_page(keyword, page, size)

# 处理 swagger UI post请求变get请求
def get_parameter_dic(request, *args, **kwargs):
  if isinstance(request, Request) == False:
    return {}

  query_params = request.query_params
  if isinstance(query_params, QueryDict):
    query_params = query_params.dict()
  result_data = request.data
  if isinstance(result_data, QueryDict):
    result_data = result_data.dict()

  if query_params != {}:
    return query_params
  else:
    return result_data
